/**
* 负责和redis memory dbsvr交互的对象
*/

#ifndef __MAINSVR_MEMORYDB_H__
#define __MAINSVR_MEMORYDB_H__

#include "maindef.h"

class CMainCtrl;
class CMainMemoryDB : public CTEpollObject<CMainMemoryDB>
{
protected:
    friend class CMainCtrl;

    /**
    * 连接的状态
    */
    enum
    {
        DB_CLOSED = 0,
        DB_CONNECTING = 1,
        DB_CONNECTED = 2,

        MEM_DB_MAX_WAIT_FOR_CHECK_SEND_COUNT = 20,
    };

    CMainCtrl*      m_pstOwner;
    CTEpoll*        m_pstEpoll;
    CTSocket        m_stSocket;
    int             m_iConnectState;
    CTBuffer        m_stRecvBuffer;
    CTBuffer        m_stSendBuffer;
    CTBuffer        m_stEncodeBuff;
    int             m_OldConnectFlag;
    int             m_ConnectCountFlag;

    int             m_iWaitForCheckSendCount;  //等待响应次数

public:
    CMainMemoryDB() :
        m_stSocket(PF_INET, SOCK_STREAM, false),
        m_iConnectState(DB_CLOSED),
        m_OldConnectFlag(DB_CLOSED),
        m_ConnectCountFlag(0),
        m_iWaitForCheckSendCount(0)
    {
    }

    int Init(CMainCtrl& stOwern, CTEpoll& stEpoll);
    void OnDBEvent(CTEpollObject<CMainMemoryDB>* pstObject, SOCKET iSocket, int iEvent);

    void CheckConnect();

    /**
    * 发送残留的请求
    */
    void CheckSend();

    int Send(const char* szKey, const char* pszBuf, int iBufLen, int iExestSecs);

protected:
    /**
    * 接收数据, 如果发现是完整的包就让MainCtrl分发处理
    */
    void Recv();

    /**
    * 用于出现收发异常时重新连接
    */
    void ReConnect();

};


#endif //__MAINSVR_MEMORYDB_H__
